
#include<iostream>
#include<string>
#include"nocopy.hpp"
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include"Log.hpp"
#include<cerrno>
#include <string.h>
#include"InetAddr.hpp"



void Usage(const std::string &process)
{
    std::cout<<"Usage:"<<process<<"server_ip server_port"<<std::endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serveip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);


    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        return 2;
    }
    std::cout << "create socket success: " << sock << std::endl;
    //2、client不需要显示绑定，client会在首次发送信息时自动绑定
    //client需要端口号，client非常多，bind随机port


    //补充server信息
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(serveip.c_str());
    server.sin_port=htons(serverport);

    while(true)
    {
        std::string inbuffer;
        //接收消息
        std::cout<<"Please Enter: ";
        std::getline(std::cin,inbuffer);

        ssize_t n=sendto(sock,inbuffer.c_str(),inbuffer.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n>0)
        {
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len=sizeof(temp);
            ssize_t m=recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
            std::cout<<sizeof(buffer);
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<" server echo :"<<buffer<<std::endl;
            }
            else
            break;

        }
        else
        break;
    }

    close(sock);

    return 0;
}